package 链表相加;


class ListNode {
    int val;
    ListNode next = null;

    public ListNode(int val) {
        this.val = val;
    }
}


public class Solution {
    /**
     * 代码中的类名、方法名、参数名已经指定，请勿修改，直接返回方法规定的值即可
     *
     * @param head1 ListNode类
     * @param head2 ListNode类
     * @return ListNode类
     */
    public ListNode addInList(ListNode head1, ListNode head2) {
        head1 = reverse(head1);

        head2 = reverse(head2);
        ListNode cur1 = head1;
        ListNode cur2 = head2;
        int t = 0;
        ListNode ret = new ListNode(0);
        ListNode cur = ret;
        while (cur1 != null || cur2 != null || t > 0) {
            if (cur1 != null) {
                t += cur1.val;
                cur1 = cur1.next;
            }
            if (cur2 != null) {
                t += cur2.val;
                cur2 = cur2.next;
            }
            cur.next = new ListNode(t % 10);
            cur = cur.next;
            t /= 10;
        }
        return reverse(ret.next);
    }

    private ListNode reverse(ListNode head) {
        ListNode cur = head;
        ListNode listNode = new ListNode(0);
        while (cur != null) {
            ListNode t = cur.next;
            cur.next = listNode.next;
            listNode.next = cur;
            cur = t;
        }
        return listNode.next;
    }
}
